package dletc.lock;

import java.util.concurrent.locks.ReentrantLock;

/*
* ReentrantLock 是jdk1.5推出的线程锁机制，作用于synchronized类似
* ReentrantLock是显示锁，需要自行释放锁,显示加锁、释放锁过程，synchronized是隐形锁，运行完毕后自动释放锁
* */
public class StudyReentrantLock {
    public static void main(String[] args) {
        TestReentrantLock reentrantLock = new TestReentrantLock();
        new Thread(reentrantLock,"A").start();
        new Thread(reentrantLock,"B").start();
        new Thread(reentrantLock,"C").start();
    }

}

class TestReentrantLock implements Runnable{

    private int ticketNum = 10;
    boolean flag = true;

    //引入ReentrantLock
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        try {
            lock.lock(); //添加锁
            while(flag){
                if(ticketNum > 0 ){
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "买到第" + ticketNum-- + "票");
                }else{
                    flag = false;
                    return;
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock(); //释放锁
        }

    }


}
